import json
from datetime import datetime

from django.http import JsonResponse

from app_server.models import QTemplateModel, JoinUserAnswersModel
from utils.IDUtil import getUUID
from utils.adaptor import qt_to_entity


# Create your views here.

# 测试连接
def test_connect(request):
    if request.method == "GET":
        return JsonResponse({"connect":"ok"})


# 1. 发布问卷调查
#    - req
#      1. 问答模版
#    - resp
#      - 链接
# test:
# {
#     "template_name": "AAA",
#     "creator_id": "1234567890",
#     "num_questions": "3",
#     "questions":[
#         {
#             "question_text":"aaaaa",
#             "flag":"0"
#         },
#         {
#             "question_text":"bbbbb",
#             "flag":"1"
#         },
#         {
#             "question_text":"bbbbb",
#             "flag":"1"
#         }
#     ],
#     "timer_duration": "2024-7-11 12:12:12"
# }
def publish_qt(request):
    if request.method == "POST":
        # 将请求的数据取出并整理
        template_name=request.POST.get("template_name",0)
        creator_id = request.POST.get("creator_id",0)
        num_questions = request.POST.get("num_questions",0)
        questions = request.POST.get("questions",0)
        timer_duration = request.POST.get("timer_duration",0)

        # 生成UUID作为链接
        template_uuid=getUUID()
        # 生成创建时间
        created_time = datetime.now()

        # 存入数据库
        orm=QTemplateModel(template_name=template_name,
                           creator_id=creator_id,
                           num_questions=num_questions,
                           questions=questions,
                           timer_duration=timer_duration,
                           template_uuid=template_uuid,
                           created_time=created_time)
        orm.save()

        # 操作成功
        return JsonResponse({"msg":"success",
                             "template_uuid": template_uuid})

# 2. 根据链接检索问卷调查
#    - req
#      1. 连接
#    - resp
#      - 问答模版
#      - 是否超时
#test:
#template_uuid=c013900e-b113-4e98-b88a-8d562fadbbd8

def find_qt_by_template_uuid(request):
    if request.method == "GET":
        # 获取QT-UUID
        template_uuid=request.GET.get("template_uuid")

        # 根据ID查找数据库
        qt=QTemplateModel.objects.get(template_uuid=template_uuid)

        # 如果查不到则返回空
        if qt==None:return JsonResponse({"msg":"success",
                                         "data":""})

        # 封装成对象
        qtEntity=qt_to_entity(qt)

        # 返回查找结果
        return JsonResponse({"msg":"success",
                             "data":qtEntity.get_template_json_formate()})


# 3. 填写并提交模版
#    - req
#      1. 用户唯一ID
#      2. 模版ID
#      3. 问题集合
#    - resp
#      - 保存是否成功

def write_qt(request):
    if request.method == "POST":
        # 获取userID
        user_id = request.POST.get("user_id",0)
        # 获取问卷ID
        template_uuid=request.POST.get("template_uuid",0)
        # 获取问题集合
        answers=request.POST.get("answers",0)

        # 设置提交时间
        created_time=datetime.now()

        # 设置提交状态
        status=1

        # 进行持久化
        orm=JoinUserAnswersModel(user_id=user_id,
                                 template_uuid=template_uuid,
                                 answers=answers,
                                 status=status,
                                 created_time=created_time)
        orm.save()

        # 操作成功
        return JsonResponse({"msg":"success"})


# 4. 我创建页面显示
#    - req
#      - 用户ID
#    - resp
#      - 多个模版

def show_created_questions(request):
    if request.method == "GET":
        # 拿到创建者ID
        creator_id=request.GET.get("creator_id")

        # 查找与创建者有关的所有问卷
        qts=QTemplateModel.objects.filter(creator_id=creator_id).order_by("-created_time")

        # 封装成对象结合
        entityList=[qt_to_entity(v).get_template_json_formate() for v in qts]

        return JsonResponse({"msg":"success",
                             "data":entityList})

# 5. 我参与页面显示
#    - req
#      - 用户ID
#    - resp
#      - 多个模版
#      - 那些超时

def show_join_questions(request):
    if request.method == "GET":
        # 拿到参与者ID
        user_id = request.GET.get("user_id")

        # 检索到参与者有关的问卷ID与对应的回答
        jua=JoinUserAnswersModel.objects.filter(user_id=user_id).order_by("-created_time")

        # 存储问卷列表
        entityList=[]
        statusList=[]

        for v in jua:

            # 拿到回答的JSON格式
            answersForJSON=v.answers

            # 找到问卷ID对应的Template
            template_uuid=v.template_uuid
            qt=QTemplateModel.objects.get(template_uuid=template_uuid)

            # 将模板类的问题转化成实体类
            qtEntity=qt_to_entity(qt)

            # 拼接将回答拼接至模版上
            qtEntity.set_questions(answersForJSON)

            # 将模板类问题转化成JSON
            qtForJSON=qtEntity.get_template_json_formate()

            # 存入集合
            entityList.insert(len(entityList),qtForJSON)
            statusList.insert(len(statusList),v.status)

        # 返回JSON响应
        return JsonResponse({"msg":"success",
                             "data":entityList,
                             "status":statusList})

# 统计数据

def sum_data(request):
    if request.method == "GET":
        # 获取问卷ID
        template_uuid = request.GET.get("template_uuid")

        # 检索到所有该问卷ID的回答
        juaList=JoinUserAnswersModel.objects.filter(template_uuid=template_uuid,status=1).order_by('-created_time')

        # 返回JSON
        return JsonResponse({"msg":"success",
                             "data":[v.answers for v in juaList],
                             "userId":[v.user_id for v in juaList]})